import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;

import fr.emse.tatiana.TatianaConstants;
import fr.emse.tatiana.display.DisplayDate;
import fr.emse.tatiana.display.DisplayFileWriter;
import fr.emse.tatiana.filter.XQueryOut;
import fr.emse.tatiana.replayable.Anchor;


public class ConvertTranscription {

	
	String xmlname;
	HashMap<Integer,Long> times = new HashMap<Integer,Long>();
    Vector<String> speakers = new Vector<String>();
    Vector<String> utterances = new Vector<String>();
    HashMap<String,String> speakerset = new HashMap<String,String>();
    int pos;
	
	
	public ConvertTranscription(String xmlname) {
		this.xmlname = xmlname;
	}

	public void writeOut(String docname, long timedelta, Map<String,String> repmap) {
		speakerset.put("","");
		speakerset.putAll(repmap);
		
		DisplayFileWriter writer = new DisplayFileWriter(xmlname);
		 int i=0;
	        long currenttime = 0;
	        while (i<pos) {
	        	if (times.get(i)!=null) {
	        		currenttime = times.get(i);
	        		i++;
	        	} else {
	        		int count = 1;
	        		while (i+count<pos && times.get(i+count)==null) {
	        			count++;
	        		}
	        		long delta = 10000*count;
	        		try {
	        			delta = (times.get(i+count)-currenttime) / (count+1);
	        		} catch (NullPointerException npe) {
	        			//was at end of array
	        		}
	        		int inc = count;
	        		while (count>0) {
	        			count--;
	        			times.put(i+count,currenttime+delta*(count+1));
	        		}
	        		i=i+inc;
	        	}	
	        }
	        
	        System.out.println("timestamps are adjusted");
	        
	        for (i=0; i<pos; i++) {
	        	writer.newItem();
	        	//System.out.println(speakers.get(i)+" : "+utterances.get(i));
	        	writer.newInfo("time", "", new DisplayDate(times.get(i)+timedelta,1000));
	        	writer.newInfo("speaker", "", speakerset.get(speakers.get(i)));
	        	writer.newInfo("contents", "", utterances.get(i));
	        	writer.newInfoFromString("src-anchor", new Anchor(docname,i).toString());
	        }
	        writer.close();
		
	}
	
	public void convert(String path,String docname, long timedelta, Map<String, String> repmap) {
        
	    try {
	    	 BufferedReader in
	    	   = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
	        String line = null;
	        String lastspeaker = "";
	        pos = 0;
	        while((line = in.readLine())!=null){
	        	if (line.matches("^\\s*$")) continue;
	        	if (line.startsWith("###")) continue;
	        	if (line.startsWith("+++")) {
	        		String time = line.split("\\s+",-1)[1];
	        		String[] timeelems = time.split("[:]");
	        		int hours = Integer.parseInt(timeelems[0]);
	        		int mins = Integer.parseInt(timeelems[1]);
	        		int msecs = (int) (Float.parseFloat(timeelems[2])*1000);
	        		times.put(pos, new Long((hours*60+mins)*60*1000+msecs));
	        	} else if (line.matches(".*:.*")) {
	        		String[] split = line.split("[:]\\s*",2);
	        		speakers.add(pos, split[0]);
	        		speakerset.put(split[0],split[0]);
	        		utterances.add(pos, split[1]);
	        		lastspeaker = split[0];
	        		pos++;
	        	} else if (line.startsWith("<")){
	        		speakers.add(pos,"");
	        		utterances.add(pos, line);
	        		pos++;
	        	} else {
	        		speakers.add(pos, lastspeaker);
	        		utterances.add(pos, line);
	        		pos++;
	        	}
	        }
	        
	        System.out.println("file is read" + path);
	        for (String speak : speakerset.keySet()) {
	        	System.out.println(speak);
	        }
	        
	        
	        // specific replacements
	        
	       writeOut(docname, timedelta, repmap);
	        
	    } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	    }
	
	}
	
	
	
//	PL:	(0:00:03.8) OK, so is everyone ready to get started then?  OK, so, what did we talk about this week?(0:00:08.1) 
//
//			M6:	The wave properties of matter
//
//			F5:	And uncertainty. (Students respond to group)
//
//			PL:	(00:18) OK, does someone want to write some stuff on the board for us?(0:00:19.8)  (Points to board)
//
//			F1:	 (0:20.1) Write equations? 
//
//			PL:	(00:20) Yeah (0:00:21.1)

	public void convertWithBrackets(String path,String docname, long timedelta, Map<String,String> repmap) {

	    try {
	    	 BufferedReader in
	    	   = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
	        String line = null;
	        String lastspeaker = "";
	        pos = 0;
	        while((line = in.readLine())!=null){
	        	if (line.matches("^\\s*$")) continue;
	        	else if (line.matches(".*:.*")) {
	        		String[] split = line.split("[:]\\s*",2);
	        		speakers.add(pos, split[0]);
	        		speakerset.put(split[0],split[0]);
	        		String utt = split[1].trim();
	        		Matcher match = Pattern.compile("\\(((\\d+):)?(\\d+):(\\d+(\\.\\d+)?)\\)", 0).matcher(utt);
	        		
	        		if (match.find()) {
	        			int hours = (match.group(1)!=null) ? Integer.parseInt(match.group(2)) : 0;
	        			int mins = Integer.parseInt(match.group(3));
	        			int msecs = (int) (Float.parseFloat(match.group(4))*1000);
	        			times.put(pos, new Long((hours*60+mins)*60*1000+msecs));
	        			utterances.add(pos, match.replaceAll(""));
	        		} else {
	        			Matcher matchangle = Pattern.compile("<(\\d+)>", 0).matcher(utt);
	        			if (matchangle.find()) {
	        				int msecs = Integer.parseInt(matchangle.group(1));
	        				times.put(pos, new Long(msecs));
	        				utterances.add(pos, matchangle.replaceAll(""));
	        			} else {
		        			utterances.add(pos, utt);
		        		}
	        		} 
	        		lastspeaker = split[0];
	        		pos++;
	        	} else if (line.startsWith("(")){
	        		speakers.add(pos,"");
	        		utterances.add(pos, line);
	        		pos++;
	        	} else {
	        		speakers.add(pos, lastspeaker);
	        		utterances.add(pos, line);
	        		pos++;
	        	}
	        }
	        
	        System.out.println("file is read" + path);
	        for (String speak : speakerset.keySet()) {
	        	System.out.println(speak);
	        }

	        
	        //broglie 1

	        
	        // specific replacements
	        
	        
	        
	        
	        writeOut(docname, timedelta, repmap);
	        
	    } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	    }
	
	}
	
	public static void main (String[] args) {
		Map<String, String> emptymap = new HashMap<String,String>();
		ConvertTranscription germinobroglie1 = new ConvertTranscription("/Users/dyke/transcript3.xml");
		germinobroglie1.convertWithBrackets("/Users/dyke/transcript3.txt","edu.cmu.cs.GS",383000,emptymap);
	}
	
	public static void main_chemistry (String[] args) {
		Map<String, String> emptymap = new HashMap<String,String>();
		ConvertTranscription germinobroglie1 = new ConvertTranscription("/Users/dyke/broglie1.xml");
		germinobroglie1.convertWithBrackets("/Users/dyke/Downloads/de_broglie_germino_review.txt","edu.cmu.cs.germinobroglie.1",0,emptymap);

		Map<String, String> brogliegerminomap1 = new HashMap<String,String>();
		brogliegerminomap1.put("PL","Peer Leader");
		brogliegerminomap1.put("PL[?]","Peer Leader[?]");
		brogliegerminomap1.put("Peer Leader [?]","Peer Leader[?]");
        
        
        //broglie 1
		brogliegerminomap1.put("Woman 1","F5");
		brogliegerminomap1.put("Woman 2","F4");
		brogliegerminomap1.put("Woman 3","F3");
		brogliegerminomap1.put("Woman 4","F2");
		brogliegerminomap1.put("Woman 5","F1");
		brogliegerminomap1.put("F1[?]","F5[?]");
		brogliegerminomap1.put("F3[?]","F3[?]");
		brogliegerminomap1.put("Man 1","M7");
		brogliegerminomap1.put("Man 2","M6");
		
		
		ConvertTranscription germinobroglie2 = new ConvertTranscription("/Users/dyke/broglie2.xml");
		germinobroglie2.convert("/Users/dyke/Downloads/CMUGDY-03.txt","edu.cmu.cs.germinobroglie.2",407000, brogliegerminomap1);

		ConvertTranscription germinobroglie3 = new ConvertTranscription("/Users/dyke/broglie3.xml");
		germinobroglie3.convertWithBrackets("/Users/dyke/Downloads/de_broglie_germino_p3.txt","edu.cmu.cs.germinobroglie.3",0,emptymap);

		
		ConvertTranscription germinobroglie5 = new ConvertTranscription("/Users/dyke/broglie5.xml");
		germinobroglie5.convert("/Users/dyke/Downloads/CMUGDY-03-bis.txt","edu.cmu.cs.germinobroglie.5",1321000, brogliegerminomap1);

		Map<String, String> brogliegerminomap2 = new HashMap<String,String>();
		brogliegerminomap2.put("PL","Peer Leader");
		brogliegerminomap2.put("PL[?]","Peer Leader[?]");
		brogliegerminomap2.put("Peer Leader [?]","Peer Leader[?]");	
		brogliegerminomap2.put("Female 5","F5"); // red top, long dark hair, latino?
		brogliegerminomap2.put("Female 3","F4"); // black+white hoodie, frizzy hair
		brogliegerminomap2.put("Female 1","F3"); // grey hoodie, blonde
		brogliegerminomap2.put("Female 4","F2"); // pink top, mediom dark hair, indian?
		brogliegerminomap2.put("Female 2","F1"); //black tshirt Blonde, deep voice
		brogliegerminomap2.put("Man 1","M7"); // yellow top, AA
		brogliegerminomap2.put("Man 2","M6"); // white top, white
		ConvertTranscription germinobroglie6 = new ConvertTranscription("/Users/dyke/broglie6.xml");
		germinobroglie6.convert("/Users/dyke/Downloads/CMUGDY-01.txt","edu.cmu.cs.germinobroglie.6",3660000, brogliegerminomap2);
		
		
		Map<String, String> periodicgerminomap1 = new HashMap<String,String>();
		periodicgerminomap1.put("PL","Peer Leader");
		periodicgerminomap1.put("PL[?]","Peer Leader[?]");
		periodicgerminomap1.put("Peer Leader [?]","Peer Leader[?]");	
		//periodicgerminomap1.put("","F5"); // salmon top, long dark hair, latino?
		//periodicgerminomap1.put("","F4"); //   black+white hoodie, frizzy hair
		//periodicgerminomap1.put("","F3"); // pink top, blonde
		//periodicgerminomap1.put("","F2"); // orange top, mediom dark hair, indian?
		//periodicgerminomap1.put("","F1"); // white tshirt Blonde, deep voice
		//periodicgerminomap1.put("","F9"); // grey top, frizzy hair - are we sure it's not F4?
		//periodicgerminomap1.put("","M7"); // red top, AA
		//periodicgerminomap1.put("","M6"); // black top, white
		ConvertTranscription germinoperiodic1 = new ConvertTranscription("/Users/dyke/periodic1.xml");
		germinoperiodic1.convertWithBrackets("/Users/dyke/Downloads/periodic_germino_review.txt","edu.cmu.cs.germinoperiodic.1",0, periodicgerminomap1);
		

		ConvertTranscription germinoperiodic2 = new ConvertTranscription("/Users/dyke/periodic2.xml");
		germinoperiodic2.convertWithBrackets("/Users/dyke/Downloads/periodic_germino_p3.txt","edu.cmu.cs.germinoperiodic.2",546000, periodicgerminomap1);
	
		Map<String, String> periodicgerminomap2 = new HashMap<String,String>();
		periodicgerminomap2.put("PL","Peer Leader");
		periodicgerminomap2.put("PL[?]","Peer Leader[?]");
		periodicgerminomap2.put("Peer Leader [?]","Peer Leader[?]");	
		periodicgerminomap2.put("Female 5","F5"); // salmon top, long dark hair, latino?
		//brogliegerminomap2.put("","F4"); //   black+white hoodie, frizzy hair
		periodicgerminomap2.put("Female 3","F3"); // pink top, blonde
		periodicgerminomap2.put("F3[?]","F3 [?]"); // pink top, blonde
		periodicgerminomap2.put("Female 3[?]","F3 [?]"); // pink top, blonde
		periodicgerminomap2.put("Female 2","F2"); // orange top, mediom dark hair, indian?
		periodicgerminomap2.put("F2[?]","F2 [?]"); // orange top, mediom dark hair, indian?
		periodicgerminomap2.put("Female[?]","F?"); 
		periodicgerminomap2.put("Female [?]","F?"); 
		periodicgerminomap2.put("Female 1","F1"); // white tshirt Blonde, deep voice
		periodicgerminomap2.put("Female 1[?]","F1 [?]");
		periodicgerminomap2.put("Female 9","F9"); // grey top, frizzy hair - are we sure it's not F4?
		periodicgerminomap2.put("Female 9[?]","F9 [?]"); // grey top, frizzy hair - are we sure it's not F4?
		periodicgerminomap2.put("F9[?]","F9 [?]"); // grey top, frizzy hair - are we sure it's not F4?
		periodicgerminomap2.put("Man 7","M7"); // red top, AA
		periodicgerminomap2.put("Man 6","M6"); // black top, white
		periodicgerminomap2.put("Man 7 [?]","M7 [?]"); // red top, AA
		periodicgerminomap2.put("Man 7[?]","M7 [?]"); // red top, AA
		periodicgerminomap2.put("Man 6 [?]","M6 [?]"); // black top, white
		ConvertTranscription germinoperiodic3 = new ConvertTranscription("/Users/dyke/periodic3.xml");
		germinoperiodic3.convert("/Users/dyke/Downloads/CMUGDY-08.txt","edu.cmu.cs.germinoperiodic.3",2838500, periodicgerminomap2);
	
		
		ConvertTranscription germinoperiodic4 = new ConvertTranscription("/Users/dyke/periodic4.xml");
		germinoperiodic4.convert("/Users/dyke/Downloads/CMUGDY-07.txt","edu.cmu.cs.germinoperiodic.4",3600000, periodicgerminomap2);
	
	}

}
